package main

import (
	"fmt"
	"io"
	"net"
	"os"
)

type Client struct {
	ServerIp   string
	ServerPort string
	Name       string
	conn       net.Conn
	Flag       int
}

func NewClientObj(serverIp, ServerPort string) *Client {
	c := &Client{
		ServerIp:   serverIp,
		ServerPort: ServerPort,
		Flag:       9999,
	}

	conn, err := net.Dial("tcp", fmt.Sprintf("%s:%s", serverIp, ServerPort))
	if err != nil {
		fmt.Printf("net.Dial error:%+v\n", err)
		return nil
	}
	c.conn = conn

	return c
}
func (this *Client) Menu() bool {
	var flag int
	fmt.Println("1.公聊模式")
	fmt.Println("2.私聊模式")
	fmt.Println("3.更新用户名")
	fmt.Println("0.退出")

	fmt.Scanln(&flag)

	if flag >= 0 && flag <= 3 {
		this.Flag = flag
		return true
	} else {
		fmt.Println(">>>>>>>请输入合法范围内的选项数字<<<<<<")
		return false
	}
}
func (this *Client) Run() {
	for this.Flag != 0 {
		for !this.Menu() {

		}
		switch this.Flag {
		case 1:
			this.PublicChat()
		case 2:
			this.PrivateChat()
		case 3:
			this.UpdateName()
		}
	}
}
func (this *Client) UpdateName() {
	fmt.Println(">>>>>请输入新的用户名")
	fmt.Scanln(&this.Name)
	sendMsg := "rename|" + this.Name + "\n"
	_, err := this.conn.Write([]byte(sendMsg))
	if err != nil {
		fmt.Printf("更新失败，请重试，Err：%+v", err)
	}
}
func (this *Client) DealResponse() {
	// 一旦client.conn有数据，就直接copy倒stdout标准输出上，永久阻塞监听
	io.Copy(os.Stdout, this.conn)
	// 等价于
	//for {
	//	buf := make([]byte, 4069)
	//	n, err := this.conn.Read(buf)
	//	if err != nil {
	//		fmt.Printf("read err：%+v\n", err)
	//		continue
	//	}
	//	fmt.Println(string(buf[:n-1]))
	//}
}
func (this *Client) PublicChat() {
	fmt.Println("请输入聊天内容，exit退出")
	var message string
	fmt.Scanln(&message)
	for message != "exit" {
		if message != "" {
			_, err := this.conn.Write([]byte(message + "\n"))
			if err != nil {
				fmt.Printf("conn write err%+v\n", err)
				break
			}
		}
		fmt.Println("请输入聊天内容，exit退出")
		message = ""
		fmt.Scanln(&message)
	}

}
func (this *Client) SelectUsers() {
	fmt.Println("请选择一个在线用户私聊，exit退出")
	_, err := this.conn.Write([]byte("who\n"))
	if err != nil {
		fmt.Printf("conn Write err%+v", err)
		return
	}
}
func (this *Client) PrivateChat() {
	this.SelectUsers()
	fmt.Println(">>>>>>>>>请输入聊天对象的【用户名】，exit退出：")
	var remoteName, message string
	fmt.Scanln(&remoteName)
	for remoteName != "exit" {
		fmt.Println(">>>>>>请输入消息内容，exit退出")
		fmt.Scanln(&message)
		for message != "exit" {
			if message != "" {
				_, err := this.conn.Write([]byte("to|" + remoteName + "|" + message + "\n\n"))
				if err != nil {
					fmt.Printf("conn Write err%+v", err)
					return
				}
				fmt.Println("请输入聊天内容，exit退出")
				message = ""
				fmt.Scanln(&message)
			}
		}
	}
}
